package com.aiyige.page.interest.edituserinterest;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.model.Page;
import com.aiyige.model.User;
import com.aiyige.model.commontag.CommonTag;
import com.aiyige.model.tag.Tag;
import com.aiyige.page.interest.edituserinterest.adapter.AlternativeAdapter;
import com.aiyige.page.interest.edituserinterest.adapter.SelectAdapter;
import com.aiyige.page.interest.model.Interest;
import com.aiyige.page.interest.searchinterest.SearchInterestPage;
import com.aiyige.page.interest.util.InterestUtil;
import com.aiyige.setup.util.SetupUtil;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UIHelper;
import com.aiyige.utils.widget.GridCommonDataView;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

@Route(path = ARouterConfig.EditUserInterestPage)
public class EditUserInterestPage extends AppCompatActivity implements GridCommonDataView.RetrofitStub {
    public static final int REQUEST_CODE_SEARCH_INTEREST = 1;
    @BindView(R.id.backBtn)
    ImageView backBtn;
    @BindView(R.id.selectNumTv)
    TextView selectNumTv;
    @BindView(R.id.maxSelectNumTv)
    TextView maxSelectNumTv;
    @BindView(R.id.confirmBtn)
    TextView confirmBtn;
    @BindView(R.id.searchBar)
    LinearLayout searchBar;
    @BindView(R.id.selectRv)
    RecyclerView selectRv;
    @BindView(R.id.alternativegcdv)
    GridCommonDataView alternativegcdv;
    @BindView(R.id.errorIv)
    ImageView errorIv;
    @BindView(R.id.errorTv)
    TextView errorTv;
    @BindView(R.id.errorLayout)
    View errorLayout;
    @BindView(R.id.loadingLayout)
    View loadingLayout;
    SelectAdapter selectAdapter;
    AlternativeAdapter alternativeAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_edit_user_interest);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        selectAdapter = new SelectAdapter();
        alternativeAdapter = new AlternativeAdapter();
        selectRv.setLayoutManager(new GridLayoutManager(this, 4));
        selectRv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.set(UIHelper.dp2px(7.5), UIHelper.dp2px(15), UIHelper.dp2px(7.5), 0);
            }
        });
        alternativegcdv.getRecyclerView().addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.set(UIHelper.dp2px(7.5), UIHelper.dp2px(15), UIHelper.dp2px(7.5), 0);
            }
        });
        selectAdapter.bindToRecyclerView(selectRv);
        alternativegcdv.config(alternativeAdapter, this);

        selectAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                try {
                    Interest interest = selectAdapter.getItem(position);
                    int index = InterestUtil.unselect(alternativeAdapter.getData(), interest);
                    if (index >= 0) {
                        alternativeAdapter.setData(index, alternativeAdapter.getItem(index));
                    }
                    adapter.remove(position);
                    autoConfigSelectNumTv();
                } catch (Exception e) {
                }
            }
        });
        alternativeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Interest interest = alternativeAdapter.getItem(position);
                if (interest.isSelected()) {
                    interest.setSelected(false);
                    alternativeAdapter.setData(position, interest);
                    int index = InterestUtil.findIndex(selectAdapter.getData(), interest);
                    if (index >= 0) {
                        selectAdapter.remove(index);
                    }
                } else {
                    if (!selectAdapter.getData().contains(interest) && selectAdapter.getData().size() >= InterestUtil.MAX_SELECTED_INTEREST_NUM) {
                        ToastX.show(StringUtils.getString(R.string.reach_max_interest_select_num, InterestUtil.MAX_SELECTED_INTEREST_NUM));
                        return;
                    }
                    interest.setSelected(true);
                    alternativeAdapter.setData(position, interest);
                    if (!selectAdapter.getData().contains(interest)) {
                        selectAdapter.addData(new Interest(interest));
                    }
                }
                autoConfigSelectNumTv();
            }
        });
        maxSelectNumTv.setText(String.valueOf(InterestUtil.MAX_SELECTED_INTEREST_NUM));
        autoConfigSelectNumTv();
        requestData();
        alternativegcdv.doRefreshRequest();
    }

    public void autoConfigSelectNumTv() {
        selectNumTv.setText(String.valueOf(selectAdapter.getData().size()));
    }

    public void requestData() {
        new RequestDataTask(this).execute();
    }

    @OnClick({R.id.backBtn, R.id.confirmBtn, R.id.errorLayout, R.id.searchBar})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.confirmBtn:
                new CommitChangeTask(this).execute();
                break;
            case R.id.errorLayout:
                requestData();
                break;
            case R.id.backBtn:
                finish();
                break;
            case R.id.searchBar:
                ARouter.getInstance()
                        .build(ARouterConfig.SearchInterestPage)
                        .withTransition(0, R.anim.activity_still)
                        .navigation(this, REQUEST_CODE_SEARCH_INTEREST);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_SEARCH_INTEREST:
                autoHandleSearchInterestResult(resultCode, data);
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    public void autoHandleSearchInterestResult(int resultCode, Intent data) {
        if (resultCode != RESULT_OK) return;
        Interest interest = data.getParcelableExtra(SearchInterestPage.EXTRA_KEY_INTEREST_DATA);
        if (interest == null) return;
        if (!selectAdapter.getData().contains(interest)) {
            if (selectAdapter.getData().size() < InterestUtil.MAX_SELECTED_INTEREST_NUM) {
                selectAdapter.addData(interest);
            } else {
                ToastX.show(StringUtils.getString(R.string.reach_max_interest_select_num, InterestUtil.MAX_SELECTED_INTEREST_NUM));
            }
        }
        if (selectAdapter.getData().contains(interest)) {
            int index = InterestUtil.findIndex(alternativeAdapter.getData(), interest);
            if (index >= 0) {
                Interest alternativeInterest = alternativeAdapter.getItem(index);
                alternativeInterest.setSelected(true);
                alternativeAdapter.setData(index, alternativeInterest);
            }
        }
        autoConfigSelectNumTv();
    }

    public void showLoadingLayout() {
        loadingLayout.setVisibility(View.VISIBLE);
        errorLayout.setVisibility(View.INVISIBLE);
    }

    public void showErrorLayout() {
        loadingLayout.setVisibility(View.INVISIBLE);
        errorLayout.setVisibility(View.VISIBLE);
    }

    public void hideCoverLayout() {
        loadingLayout.setVisibility(View.INVISIBLE);
        errorLayout.setVisibility(View.INVISIBLE);
    }

    @Override
    public Call<ResponseBody> call(long currentPage) {
        return ApiManager.getService().recommendInterestForUser(currentPage, 40);
    }

    @Override
    public GridCommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<Tag> tagList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                tagList.addAll(JSON.parseArray(page.getContent(), Tag.class));
            }
            List<Interest> interestList = InterestUtil.convertTagListToInterestList(tagList);
            InterestUtil.resumeSelect(interestList, selectAdapter.getData());
            resultList.addAll(interestList);
            return new GridCommonDataView.HandleResult(page.isLast());
        } catch (Exception e) {
            return new GridCommonDataView.HandleResult(e.getMessage());
        }
    }

    public class RequestDataTask extends SafeAsyncTask<Object, Object, Object> {
        List<Interest> selectedInterestList = new LinkedList<>();

        public RequestDataTask(Activity activity) {
            super(activity);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingLayout();
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
                ToastX.show((Exception) o);
                showErrorLayout();
            } else {
                hideCoverLayout();
                selectAdapter.setNewData(selectedInterestList);
            }
            autoConfigSelectNumTv();
        }


        @Override
        protected Object doInBackground(Object... objects) {
            try {
                List<Tag> columnBackup;
                try {
                    Response<ResponseBody> response = ApiManager.getService()
                            .userCenterUsers(AccountUtil.getCurrentUser().getId())
                            .execute();
                    if (response.code() != ResponseCode.OK) {
                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                    }
                    String json = RetrofitUtil.getResponseBodyAsString(response);
                    User tempUser = JSON.parseObject(json, User.class);
                    List<Tag> serverColumnBackup = ListUtil.isEmpty(tempUser.getAvocation()) ? new LinkedList<Tag>() : tempUser.getAvocation();
                    columnBackup = serverColumnBackup;
                } catch (Exception e) {
                    columnBackup = AccountUtil.getCurrentUser().getAvocation();
                }
                selectedInterestList.addAll(InterestUtil.convertTagListToInterestList(columnBackup));
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }

    public class CommitChangeTask extends SafeAsyncTask<Object, Object, Object> {

        public CommitChangeTask(Activity activity) {
            super(activity, R.string.text_process);
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
                ToastX.show((Exception) o);
            } else {
                getActivity().finish();
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().userCenterUsers(AccountUtil.getCurrentUser().getId(), User.newBuilder()
                        .avocation(InterestUtil.convertInterestListToTagList(selectAdapter.getData()))
                        .channel(Tag.newBuilder().build())
                        .build())
                        .execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                User tempUser = JSON.parseObject(json, User.class);
                User user = AccountUtil.getCurrentUser();
                user.update(tempUser);
                AccountUtil.updateCurrentUser(user);
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }
}
